const express = require('express');
//引入cors模块
const cors = require('cors');
const joi = require('joi');
const app = express();

app.listen(3000,()=>{
    console.log('服务器已启动.....');
});
//添加跨域 中间件
app.use(cors());
//托管静态资源
app.use('/imgs',express.static('./resource'));
//配置解析表单数据中间件
app.use(express.urlencoded({extended:false}));

//封装 res.cc函数用于发送错误
app.use((req,res,next)=>{
    res.cc = function(err,status  = 1){
        res.send({
            status,message:err instanceof Error ? err.message : err,
        })
    };
    next();
});
//配置解析Token的 中间件
const expressJWT = require('express-jwt');
const config = require('./config.js');

app.use(expressJWT({secret:config.jwtSecretKey}).unless({path:[/^\/admin || ^\/api || ^\/goodboy  /]}));

//引入并挂载路由
app.use('/api',require('./router/rmdRouter.js'));
app.use('/goodboy',require('./router/selfMachineRouter.js'));
app.use('/admin',require('./router/user.js'));
//定义错误处理中间件

app.use(function(err,req,res,next){
    
    //验证失败的错误
    if(err instanceof joi.ValidationError) return res.cc(err);

    //身份认证失败后的错误
    if(err.name == 'UnauthorizedError') return res.cc('身份验证失败，请重新登录！');
    //未知的错误
 

    res.cc(err);


    
    next();
});